#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/10/19 15:11
# file: user.py
# author: lotus163
from typing import Optional

from fastapi import APIRouter, Depends

from backend.core.deps import UserDepends, get_user_depends, get_user_depends_nolog
from backend.core.result import Result, result_success, ResultList, result_success_no_log
from backend.crud import LoginInforDao
from backend.schemas import LoginInforSch
from backend.utils.string_util import get_array_by_str

router = APIRouter(prefix="/logininfor", tags=["登录日志"])


@router.delete("/clean", response_model=Result, summary='清除登录日志')
async def clean_login_logs(user_depends: UserDepends = Depends(get_user_depends)):
    await LoginInforDao.get_list_queryset().delete()
    return result_success()


@router.post("/export", response_model=Result, summary='导出登录日志列表')
async def export_login_logs():
    pass


@router.get("/list", response_model=ResultList[LoginInforSch], summary='获取登录日志列表')
async def get_login_logs(pageNum: int, pageSize: int, ipaddr: Optional[str] = None,
                         userName: Optional[str] = None, status: Optional[str] = None,
                         user_depends: UserDepends = Depends(get_user_depends_nolog)):
    # 准备查询的参数
    form = LoginInforSch(userName=userName, ipaddr=ipaddr, status=status)
    form_dict = form.dict(exclude_none=True)
    # 时间
    start, end = user_depends.request_service.get_params_time()
    if (start is not None) and (end is not None):
        form_dict["loginTime__range"] = (start, end)
    # 查询
    login_infors_sch = await LoginInforDao.get_list_sch_page(pageSize=pageSize, pageNum=pageNum, **form_dict)
    total = await LoginInforDao.get_list_count(**form_dict)
    return result_success_no_log(msg="查询成功", rows=login_infors_sch, total=total)


@router.get("/unlock/{userName}", response_model=Result, summary='根据username解锁账户')
async def unlock_login_log(userName: str):
    return result_success()


@router.delete("/{infoIds}", response_model=Result, summary='根据ids删除登录日志')
async def remove_login_logs(infoIds: str, user_depends: UserDepends = Depends(get_user_depends)):
    info_ids = get_array_by_str(infoIds)
    await LoginInforDao.get_list_queryset(infoId__in=info_ids).delete()
    return result_success()
